
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

public class Encryption {
    
    // Secret key
    // Length must be 16 bytes
    private static byte[] key = {
            0x62, 0x65, 0x73, 0x74, 0x52, 0x61, 0x64, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x32, 0x30, 0x31, 0x33
    };

    /**
     * encrypt
     * @param str String to be encrypt
     * @desc Encrypts a string using AES
     * @return Returns an encrypted string 
     */
    public String encrypt(String str) {
        try {
            // Define encryption mode
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            
            // Define secret key
            final SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
            
            // Init encryption
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            
            // Encrypt
            final String encryptedString = Base64.encodeBase64String(cipher.doFinal(str.getBytes()));
            
            // Return encrypted string
            return encryptedString;
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    public String decrypt(String str) {
        try {
            // Define encryption mode
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            
            // Define secret key
            final SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
            
            // Init encryption
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            
            // Decrypt
            final String decryptedString = new String(cipher.doFinal(Base64.decodeBase64(str)));
            
            // Return decrypted value
            return decryptedString;
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
